package edu.cmu.vlis.wassup.sender;

import java.util.HashSet;
import java.util.Set;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Topic;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.RollbackException;

import edu.cmu.vlis.wassup.databean.Event;
import edu.cmu.vlis.wassup.databean.User;
import edu.cmu.vlis.wassup.db.EventsForUserDAO;
import edu.cmu.vlis.wassup.db.UserDAO;
import edu.cmu.vlis.wassup.db.UserInterestDAO;
import edu.cmu.vlis.wassup.utils.MailClient;

public class TopicQueueFetcher implements MessageListener, Runnable{
	DBHandler dbHandler = null;
	Topic topic;

	Event ann;
	String ret = null;
	Set<User> users = null;

	TopicQueueFetcher(Topic topic) {
		this.topic = topic;
		this.initialize();
	}

	public void initialize(){
        try{
            this.dbHandler = DBHandler.getInstance();
            dbHandler.setTopic(topic.getTopicName());
        }catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch(Exception e){
            System.err.println("Couldnt connect to DB.");
            //e.printStackTrace();
            }
	    
	}
	public void onMessage(Message message) {
		System.err.println("I received a message");
		ObjectMessage objMesg = (ObjectMessage)message;
		Event a;
		try {
			a = (Event) objMesg.getObject();
			//test(a); /*test if u get an Event properly*/		
			if(this.dbHandler == null)
			    this.initialize();
			ret = this.dbHandler.commitToDB(a);
			if(ret!=null){
				ann = a;
				//fetch the users who are interested tag and send emails
				fetchProfile();
				//Make an entry in the user-Event table
				sendAlerts();
				System.out.println("1 message insrted in the database.");
			}
			else {
				System.err.println("Already in DB. Hence no processing");
			}
		} catch (JMSException e) {
			System.out.println("Error in connecting to JMS");
			// TODO Auto-generated catch block
			System.out.println(e.toString());
		}catch (Exception e){
			e.printStackTrace();
		    System.err.println("Error while inserting message in DB.");
		}
	}

	
	void test(Event ann) {
		String subject= "Whats up Event on " + ann.getStartDate() + " " + ann.getStartTime() +  
		" in " + ann.getCity();
		String message=  "What : " + ann.getName()+"\n"+
		"Where: " + ann.getStreet()+ "," + ann.getCity() + "," + ann.getState() + "\n" + 
		"When: " + ann.getStartDate() + " - " + ann.getEndDate() + "\n" + 
		"Time : " + ann.getStartTime() + " - " + ann.getEndTime() + "\n";
		System.out.println(subject + "\n" + message);
	}

	void sendAlerts() {
		if (users==null || users.size()==0) {
			
			System.out.println("sendAlerts : users NULL" );
			
			return;
		}
		for(User p : users) {
			//Get Emails for the user
						
			System.out.println(p);
			
			//build the message
			if(ann!=null) {
				String subject= "Whats up Event on " + ann.getStartDate() + " " + ann.getStartTime() +  
				" in " + ann.getCity();


				String message=  "What : " + ann.getName()+"\n"+
				"Where: " + ann.getStreet()+ "," + ann.getCity() + "," + ann.getState() + "\n" + 
				"When: " + ann.getStartDate() + " - " + ann.getEndDate() + "\n" + 
				"Time : " + ann.getStartTime() + " - " + ann.getEndTime() + "\n";

				if(ann.getUrl()!=null && ann.getUrl()!="" && ann.getUrl()!=" ")
					message = message + "Have a look at :" + ann.getUrl();
				//Send the mail 
				try  
				{ 
					MailClient client = new MailClient();  
					String to = p.getUserName();
					System.out.println("Sending email to " + to);
					client.sendMail(to,subject,message);

					EventsForUserDAO apm = new EventsForUserDAO();
					apm.insert(ann,p);
				} 
				catch(Exception e) 
				{ 
					continue;
				}

			}else 
				System.out.println("Didnot Retrieve the message!");
		}
	}
	void fetchProfile(){
		User[] userLoc;
		User[] userTag;
		

		try {
			UserDAO um = new UserDAO();
			UserInterestDAO uim = new UserInterestDAO();
			
			
			userLoc =  um.getLocationUsers(ann.getCity());
			
			if(topic.getTopicName()!=null) {
				userTag  = uim.getUsersInterestedIn(topic.getTopicName());
				//Intersection of two Users
				Set <User> u1 = new HashSet<User>();
				for(int i=0;i<userLoc.length;i++) {
				 u1.add(userLoc[i]);
			}
			Set <User> u2 = new HashSet<User>();
			for(int i=0;i<userTag.length;i++) {
			 u2.add(userTag[i]);
			}
			u1.retainAll(u2);
			   users = u1; 
			}
			
		} catch (RollbackException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void run() {
		// TODO Auto-generated method stub
	}
}
